package com.yoda.mall.mysql.api;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yoda.mall.api.ResourceApi;
import com.yoda.mall.api.RoleResourceRelationApi;
import com.yoda.mall.model.entity.ums.Resource;
import com.yoda.mall.model.vo.PageResult;
import com.yoda.mall.model.vo.R;
import com.yoda.mall.mysql.mapper.ResourceMapper;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

@DubboService
public class ResourceApiImpl implements ResourceApi {
    @Autowired
    private ResourceMapper resourceMapper;
    @Autowired
    private RoleResourceRelationApi roleResourceRelationApi;

    @Override
    public List<Resource> listAll() {
        LambdaQueryWrapper<Resource> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByAsc(Resource::getCategoryId);
        return resourceMapper.selectList(wrapper);
    }

    @Override
    public PageResult<Resource> pageList(Integer categoryId, String nameKeyword, String urlKeyword, Integer pageNum, Integer pageSize) {
        Page<Resource> page = new Page<>(pageNum,pageSize);
        LambdaQueryWrapper<Resource> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ObjectUtil.isNotNull(categoryId),Resource::getCategoryId,categoryId)
                .like(ObjectUtil.isNotNull(nameKeyword),Resource::getName,nameKeyword)
                .like(ObjectUtil.isNotNull(urlKeyword),Resource::getUrl,urlKeyword)
                .orderByAsc(Resource::getId);
        resourceMapper.selectPage(page, wrapper);
        return new PageResult<Resource>(pageNum,pageSize, Convert.toInt(page.getTotal()),page.getRecords());
    }

    @Override
    public void create(Resource resource) {
        resourceMapper.insert(resource);
    }

    @Override
    public void deleteById(Integer id) {
        resourceMapper.deleteById(id);
        roleResourceRelationApi.deleteByResourceId(id);
    }

    @Override
    public void updateById(Resource resource) {
        resourceMapper.updateById(resource);
    }

    @Override
    public Resource findById(Integer id) {
        return resourceMapper.selectById(id);
    }

    @Override
    public List<Resource> findByCategoryId(Integer id) {
        LambdaQueryWrapper<Resource> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Resource::getCategoryId,id);
        return resourceMapper.selectList(wrapper);
    }

}
